<?php
class DealOrder extends AppModel {

	var $name = 'DealOrder';
	const STATUS_PENDING = 0;
	const STATUS_COMPLETE = 1;
	const STATUS_FAILED = 2;
	
	var $validate = array(
			'quantity' => array(
					'notempty'=>array(
							'rule' => VALID_NOT_EMPTY,
							'message' => "This field is required"
					),
					'validCheck'=>array(
							'rule' => '/^\d+$/',
							'message' => "Entered value should be greater than or equal to zero",
							'required' => false,
							'allowEmpty' => true
					)
			),
	);
	
	var $fieldProperties = array(
			'quantity'=>array(
					'label'=>'Quantity',
					'group'=>array('add','edit','view'),
					'type'=>"select",
					'options' => array()
			),
	);

	//The Associations below have been created with all possible keys, those that are not needed can be removed
	var $belongsTo = array(
		'Deal' => array(
			'className' => 'Deals.Deal',
			'foreignKey' => 'deal_id',
			'conditions' => '',
			'fields' => '',
			'order' => ''
		),
		'User' => array(
			'className' => 'Users.User',
			'foreignKey' => 'user_id',
			'conditions' => '',
			'fields' => '',
			'order' => ''
		)
	);
	
	var $hasMany = array(
			'DealOrderCode' => array(
					'className' => 'Deals.DealOrderCode',
					'foreignKey' => 'deal_order_id',
					'dependent'=>true,
			),
	);
	var $additionalFields = array(
			'paymentTransactionId'
	);
	
	function paymentTransactionId($result)
	{
		$return = "";
		if(isset($result[$this->alias]['admin_note']['txn_id']) && !empty($result[$this->alias]['admin_note']['txn_id']))
		{
			$return = $result[$this->alias]['admin_note']['txn_id'];
		}
		return $return;
	}
	
	
	function initialize()
	{
		parent::initialize();
		$this->setFieldProperties("admin_note", array("fieldModifier"=>"toggleSerialized"));
	}
	
	function saveOrder($data)
	{
		$return = false;
		if(isset($data[$this->alias]['quantity']) && $data[$this->alias]['quantity']>0)
		{
			$deal = $this->Deal->find("first",array("conditions"=>array("Deal.id"=>$data[$this->alias]['deal_id']),"recursive"=>-1));
			$dealConfig = cr("DealConfig");
			$taxRate = $dealConfig['tax'];
			$tax = 0;
			if(!$taxRate)
			{
				$taxRate = 0;
			}
			$orderCodes = array();
			$totalAmount = 0;
			if(!empty($deal))
			{
				$totalAmount = ($deal['Deal']['finalPrice'] * $data[$this->alias]['quantity']);
				if($taxRate)
				{
					$tax = (($totalAmount / 100) * $taxRate);
					$totalAmount = ($totalAmount + $tax);
				}
				$data[$this->alias]['amount'] = $totalAmount;
				$data[$this->alias]['currency'] = $dealConfig['currency'];
				$data[$this->alias]['currency_symbol'] = $dealConfig['currency_symbol'];
				$data[$this->alias]['tax'] = $tax;
				$data[$this->alias]['tax_rate'] = $taxRate;
				for($i = 0; $i < $data[$this->alias]['quantity']; $i++)
				{
					$orderCodes[] = array(
						'amount'=>$deal['Deal']['finalPrice'],
						'deal_code' => $this->DealOrderCode->generateRandomUniqueValue("deal_code")
					);
				}
				$data['DealOrderCode'] = $orderCodes;
				$this->create();
				$return = $this->saveAll($data);
				/*
				 * commented as client wanted to increase consumed deals only on payment completion
				if($return)
				{
					$this->Deal->id = $deal['Deal']['id'];
					$this->Deal->saveField("quantity_consumed",($deal['Deal']['quantity_consumed'] + $data[$this->alias]['quantity']),false,false);
				}
				*/
			}
		}
		return $return;
	}
	
	function markAllUsed($id)
	{
		$dealOrder = $this->find("first",array("conditions"=>array("DealOrder.id"=>$id),"recursive"=>-1));
		if(!$id || empty($dealOrder))
		{
			return false;
		}
		$return = false;
		if($this->updateAll(array('DealOrder.is_used'=>1,'DealOrder.used_on'=>date("Ymd")),array("DealOrder.id"=>$id)))
		{
			$return = $this->DealOrderCode->updateAll(array('DealOrderCode.is_used'=>1,'DealOrderCode.used_on'=>date("Ymd")),array("DealOrderCode.deal_order_id"=>$id));
		}
		return $return;
	}
	function setAsCompleted($orderId, $ipnValidateData = null)
	{
		$return = false;
		$dealOrder = $this->find("first",array("conditions"=>array($this->alias.".id"=>$orderId),"recursive"=>0));
		if($orderId && !empty($dealOrder))
		{
			$this->id = $orderId;
			if($this->saveField('status',self::STATUS_COMPLETE,false,false))
			{
				$return = true;
				if(!empty($ipnValidateData))
				{
					$this->id = $orderId;
					$this->saveField('admin_note',$ipnValidateData,false);
				}
				if(isset($dealOrder['Deal']['id'])) 
				{
					$this->Deal->id = $dealOrder['Deal']['id'];
					$this->Deal->saveField("quantity_consumed",($dealOrder['Deal']['quantity_consumed'] + $dealOrder[$this->alias]['quantity']),false,false);
				}
			}
		}
		return $return;
	}
	
	function setAsFailed($orderId, $ipnValidateData = null)
	{
		$return = false;
		$dealOrder = $this->find("first",array("conditions"=>array($this->alias.".id"=>$orderId),"recursive"=>0));
		if($orderId && !empty($dealOrder))
		{
			$this->id = $orderId;
			if($this->saveField('status',self::STATUS_FAILED,false,false))
			{
				$return = true;
				if(!empty($ipnValidateData))
				{
					$this->id = $orderId;
					$this->saveField('admin_note',$ipnValidateData,false);
				}
			}
		}
		return $return;
	}

	
}